package cn.com.nes.site.module.dao.newmall;

import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.Page;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionStatus;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository

public class NewmallBookingDaoImpl extends BaseDaoImpl {
    private TransactionStatus newg_status = null;

    public PageData saveBookingInfo(Connection conn, DataReq req) throws SQLException {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("预约信息保存失败");
        StringBuffer sb = new StringBuffer();

        param.put("tableName", "newshop_booking_info");
        String uuid = (String) param.get("uuid");
        String bookingStatus = (String) param.get("bookingStatus");//0待进店 1已完成 2已取消
        if (StringUtils.isEmpty(uuid)) {
            String yyr_phone = (String) param.get("yyr_phone");
            String product_id = (String) param.get("product_id");
            String mer_id = (String) param.get("mer_id");
            sb.delete(0,sb.length());
            sb.append(" select uuid from newshop_booking_info where isdelete=0 and booking_status = 0 and DATE_FORMAT(createTime,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d') and mer_id =? and yyr_phone=? ");
            if (StringUtils.isEmpty(product_id))
                sb.append(" and (product_id = '' or product_id is NUll) ");
            else
                sb.append(" and product_id= '" + product_id + "' ");
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{mer_id, yyr_phone});
            if (list == null || list.size() == 0) {
                param.put("uuid", DBUtils.getDjbh(req.getUinfo().getCompanyId(), "NO_"));
                param.put("booking_status", "0");
                param.put("isdelete", "0");
                res = insertTableData(conn, req);
            } else {
                res.setRetCode(9);
                res.setRetMessage("您已成功预约，请勿重复操作！");
            }
        } else if (StringUtils.isNotEmpty(uuid)) {
            param.put("keys", "uuid");
            param.put("uuid", uuid);
            param.put("booking_status", bookingStatus);
            res = updateTableData(conn, req);

            //修改线索 取消预约 线索跟进状态修改为 06商城预约取消
            sb.delete(0, sb.length());
            sb.append("select uuid from clue where newshopBookingId is not null and newshopBookingId <> '' and newshopBookingId=? and isdelete=0 and sfzx=1 ");
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{uuid});
            //修改线索跟进状态
            if (list !=null && list.size()>0) {
                try {
                    newg_status = begin_newg();// 开启事务
                    sb.delete(0, sb.length());
                    sb.append("update clue set followupstatus='06',modifyUid=?,modifyTime=now() where uuid=?");
                    this.getJdbcTemplate_newg().update(sb.toString(), new Object[]{req.getUinfo().getId(), list.get(0).get("uuid")});
                    commit_newg(newg_status);
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    rollback_newg(newg_status);
                }
            }
            param.put("OperationLogName", "修改线索跟进状态");
            param.put("OperationLogType", "01");
            updateTableData(conn, req) ;
        } else {
            res.setRetCode(9);
            res.setRetMessage("操作失败！");
        }
        if (res.getRetCode() == 0) {
            res.setRetCode(0);
            res.setRetMessage("OK");
        }
        return res;
    }

    public PageData getBookingList(DataReq req) throws SQLException {
        HashMap<String, Object> param = req.getReqData();
        String booking_status = (String) param.get("bookingStatus");
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取预约信息失败");
        Connection conn = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer();
            sb.append(" select nbi.uuid,nbi.yyr_name,nbi.yyr_phone,nbi.yjjd_time,date_format(nbi.createTime,'%Y-%m-%d %T') as createTime,nbi.product_id,nbi.mer_id,nbi.booking_status,tp.name as bookingStatusName,tc.companyName,tc.address,tc.shortname,tc.longitude,tc.latitude,tc.contactNumber " +
                    " from newshop_booking_info nbi" +
                    " left join t_param tp on nbi.booking_status=tp.value and tp.param_type='30' "+
                    " left join t_company tc on nbi.mer_id=tc.mer_id and tc.mer_id <> '' and tc.mer_id is not null and isnewshop='1' " +
                    " where isdelete=0 ");
            if (StringUtils.isNotEmpty(booking_status)) {
                sb.append(" and booking_status = '").append(booking_status).append("'");
            }
            sb.append(" and nbi.createUid= ? ");
            sb.append(" order by nbi.createTime desc ");
            //分页
            sbfrom.append(sb.toString());
            int idx = sbfrom.indexOf(" from ");
            sbfrom.delete(0, idx);
            Page page = new Page(conn, sbfrom.toString(), req.getPageid(), req.getPagesize(), res, new Object[]{req.getUinfo().getId()});
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize());
            List<Map<String, Object>> list = this.queryForList(conn, sb.toString(), new Object[]{req.getUinfo().getId()});

            for (Map<String, Object> map : list) {
                sb.delete(0, sb.length());
                sb.append(" select `name` store_name from eb_product where id=? ");
                List<Map<String, Object>> storeNameList = this.getJdbcTemplate_mall().queryForList(sb.toString(),new Object[] {map.get("product_id")});
                map.put("store_name", storeNameList.size() == 0 ? "" : storeNameList.get(0).get("store_name"));
            }
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return res;
    }

    public  Map<String, Object> getCompanyById(DataReq req) throws SQLException {
        HashMap<String, Object> param = req.getReqData();
        String mer_id = (String) param.get("mer_id");
        Map resMap=new HashMap<>();
        Connection conn = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            StringBuffer sb = new StringBuffer();
            sb.delete(0, sb.length());
            sb.append(" select companyId,areacode,longitude,latitude from t_company where mer_id =? and sfsc=0 and isnewshop='1' ");
            List<Map<String, Object>> list = this.queryForList(conn, sb.toString(), new Object[]{mer_id});
            resMap.putAll(list.size()>0?list.get(0):resMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.close();
        }
        return resMap;
    }

}
